'''
Created on Nov 29, 2010

@author: dexen
'''

import time
import random

from dexen import BaseSlaveTask
from dexen.libs import ranking
from dexen.libs.ranking import ParetoRanking


def select(inds):    
    inds = sorted(inds, key=lambda rank: rank.id)
    size = len(inds)
    return inds[:size/2], inds[size/2:]

def create_new_gen(inds):
    assert len(inds) % 2 == 0
    random.shuffle(inds)
    new_gen = []
    for i in range(0, len(inds), 2):
        child1, child2 = inds[i].reproduce(inds[i+1])
        new_gen.append(child1)
        new_gen.append(child2)
    return new_gen


class FeedbackTask(BaseSlaveTask):
    def __init__(self):
        pass
    
    def __execute__(self, master_state, inds):
        print "I am in Feedback"
    
        p_ranking = ParetoRanking(inds)
        p_ranking.register_score("evalA", ranking.MINIMIZE)
        p_ranking.register_score("evalB", ranking.MINIMIZE)
        ranked = p_ranking.rank() # returns list of RankResult sorted by rank
        #ranked = p_ranking.get_ranked()
        
        assert len(inds) == len(ranked)
        #alive_inds, dead_inds = select(inds)
        
        alive_inds = [x.ind for x in ranked[:len(inds)/2]]
        dead_inds = [x.ind for x in ranked[len(inds)/2:]]
        
        print "Alive ones"
        for ind in alive_inds:
            print ind

        print "Dead ones"
        for ind in dead_inds:
            ind.kill()
            print ind
                
        new_gen = create_new_gen(alive_inds)
        return inds + new_gen
        

    